package cn.csg.iotplatform.module.system.controller.admin.dept;

import cn.csg.iotplatform.framework.common.enums.CommonStatusEnum;
import cn.csg.iotplatform.framework.common.pojo.CommonResult;
import cn.csg.iotplatform.framework.common.pojo.PageResult;
import cn.csg.iotplatform.framework.common.util.object.BeanUtils;
import cn.csg.iotplatform.framework.datapermission.core.annotation.DataPermission;
import cn.csg.iotplatform.framework.web.core.util.WebFrameworkUtils;
import cn.csg.iotplatform.module.system.controller.admin.dept.vo.dept.*;
import cn.csg.iotplatform.module.system.dal.dataobject.dept.AdminAreaDO;
import cn.csg.iotplatform.module.system.dal.dataobject.dept.DeptDO;
import cn.csg.iotplatform.module.system.dal.dataobject.dept.DeptWithParentDO;
import cn.csg.iotplatform.module.system.service.dept.DeptService;
import cn.csg.iotplatform.module.system.service.org.OrgService;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

import static cn.csg.iotplatform.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 部门")
@RestController
@RequestMapping("/system/dept")
@Validated
public class DeptController {

    @Resource
    private DeptService deptService;
    @Resource
    private OrgService orgService;

    @PostMapping("create")
    @Operation(summary = "创建部门")
    @PreAuthorize("@ss.hasPermission('system:dept:create')")
    public CommonResult<Long> createDept(@Valid @RequestBody DeptSaveReqVO createReqVO) {
        Long deptId = deptService.createDept(createReqVO);
        return success(deptId);
    }

    @PutMapping("update")
    @Operation(summary = "更新部门")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<Boolean> updateDept(@Valid @RequestBody DeptSaveReqVO updateReqVO) {
        deptService.updateDept(updateReqVO);
        return success(true);
    }

    @DeleteMapping("delete")
    @Operation(summary = "删除部门")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:dept:delete')")
    public CommonResult<Boolean> deleteDept(@RequestParam("id") Long id) {
        deptService.deleteDept(id);
        return success(true);
    }

    @GetMapping("/list")
    @Operation(summary = "获取部门列表")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<PageResult<DeptRespVO>> getDeptList(DeptListReqVO reqVO) {
        PageResult<DeptWithParentDO> list = deptService.getDeptListWithParent(reqVO);
        return success(BeanUtils.toBean(list, DeptRespVO.class));
    }

    @GetMapping(value = {"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门，主要用于前端的下拉选项")
    public CommonResult<List<DeptSimpleRespVO>> getSimpleDeptList() {
        List<DeptDO> list = deptService.getDeptList(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));
        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "获得部门信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<DeptRespVO> getDept(@RequestParam("id") Long id) {
        DeptDO dept = deptService.getDept(id);
        return success(BeanUtils.toBean(dept, DeptRespVO.class));
    }

    @GetMapping("/tree")
    @Operation(summary = "获得部门信息列表树", description = "只包含被开启的部门，主要用于前端生成部门树")
    @Parameter(name = "id", description = "部门id", required = true)
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<Object> getDeptTree(DeptTreeDto deptTreeDto) {
        List<Tree<Object>> deptTree = deptService.getDeptTree(deptTreeDto, true);
        return success(deptTree);
    }

    //获得4A部门树
    @GetMapping("/get4ATree")
    @Parameter(name = "id", description = "部门id", required = true, example = "520")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<Object> get4ATree(DeptTreeDto deptTreeDto) {
        List<Tree<Object>> deptTree = deptService.getDeptTree(deptTreeDto, false);
        return success(deptTree);
    }

    @GetMapping("/getUdrTree")
    @Operation(summary = "获取用户所属组织+关联组织树")
    public CommonResult<List<Tree<Long>>> getUdrTree() {
        return success(deptService.getUdrTree());
    }

    @GetMapping("/getLazyTree")
    @Parameter(name = "id", description = "部门id", required = true, example = "520")
    @DataPermission(enable = false)
    public CommonResult<List<Tree<Long>>> getLazyTree(DeptTreeSearchVO searchVO) {
        return success(deptService.getLazyTree(searchVO));
    }

    @PostMapping("/updateDeptTree")
    @Operation(summary = "添加或移除系統组织机构")
    @Parameter(name = "useFlag", description = "是否被引用", required = true, example = "1-添加引用0-移除引用")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    @DataPermission(enable = false)
    public CommonResult<Boolean> updateSystemDept(@RequestParam("useFlag") Integer useFlag, @RequestBody List<Long> ids) {
        deptService.batchUpdateUseFlag(ids, useFlag);
        return success(true);
    }

    @PutMapping("/batchSave")
    @Operation(summary = "批量保存机构数据")
    @Parameter(description = "部门更新数据集合", required = true, example = "[{'id':100,'shortName':'南网'}]")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<Boolean> batchSave(@RequestBody List<DeptListSaveReqVO> list) {
        deptService.batchSave(list);
        return success(true);
    }

    @GetMapping("/getDeptAreaSetting")
    @Operation(summary = "查询行政区域设置")
    @Parameter(name = "deptId",description = "部门id", required = true, example = "100")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<List<AdminAreaDO>> getDeptAreaSetting(@RequestParam("deptId") Long deptId) {
        return success(deptService.selectAdminAreaSetting(deptId));
    }

    @GetMapping("/getAdminAreaList")
    @Operation(summary = "查询行政区域列表")
    @Parameters({
            @Parameter(name = "type",description = "关联行政区域类型", required = true, example = "0"),
            @Parameter(name = "provinceCode",description = "省级行政编码", example = "40000")
    })
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<List<AdminAreaDO>> getAdminAreaList(@RequestParam("type") Integer type,@RequestParam(value = "provinceCode",required = false) String provinceCode) {
        return success(deptService.getAdminAreaList(type,provinceCode));
    }

    @PostMapping("/saveDeptAreaSetting")
    @Operation(summary = "保存部门行政区域设置")
    @Parameters({
            @Parameter(name = "deptId",description = "部门id", required = true, example = "100"),
            @Parameter(name = "type",description = "关联行政区域类型", required = true, example = "0"),
            @Parameter(name = "codes",description = "行政区域编码", required = true, example = "0")
    })
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<Boolean> saveDeptAreaSetting(@RequestParam("deptId") Long deptId,
                                                     @RequestParam("type")Integer type,
                                                     @RequestParam("codes")String codes) {
        return success(deptService.saveDeptAreaSetting(deptId,type,StrUtil.split(codes,",")));
    }

    @GetMapping("/getUserDeptRelation")
    @Operation(summary = "获得用户关联部门list")
    @Parameter(name = "userId", description = "用户id", required = true, example = "520")
    @DataPermission(enable = false)
    public CommonResult<List<Map<String, Object>>> getUserDeptRelation(@RequestParam("userId") Long userId) {
        return success(deptService.getUserDeptRelation(userId));
    }

    /**
     * 刷新部门id全路径
     */
    @GetMapping("/updateFullPath")
    @Parameter(name = "pathFieldName", description = "存放全路径的字段", required = true, example = "FULL_PATH_ID")
    @PreAuthorize("@ss.hasPermission('system:dept:updateFullPath')")
    public void updateFullPathId(@RequestParam("pathFieldName") String pathFieldName) {
        deptService.updateFullPathId(pathFieldName);
    }

    @GetMapping("/syncPlatformUsingData")
    @PreAuthorize("@ss.hasPermission('system:dept:syncPlatformUsingData')")
    public void syncPlatformUsingData(@RequestParam(value = "clear", required = false, defaultValue = "false") boolean clear) {
        orgService.synRemoteOrgData2Local(clear+"");
    }

    @GetMapping("/syncEquipCenterOrgData")
    @PreAuthorize("@ss.hasPermission('system:dept:syncEquipCenterOrgData')")
    public void syncEquipCenterOrgData() {
        orgService.synRemoteEquipCenterOrgData2Local();
    }

    @GetMapping("/updateIdAndNameFullPath")
    @PreAuthorize("@ss.hasPermission('system:dept:updateIdAndNameFullPath')")
    public void updateFullPath() {
        deptService.updateFullPath();
    }

    @GetMapping("/updateLeafProp")
    @PreAuthorize("@ss.hasPermission('system:dept:updateLeafProp')")
    public void updateLeafProp() {
        deptService.updateLeafProp();
    }

    @GetMapping("/getUserDeptList")
    @Operation(summary = "获取当前用户所属单位及借调单位")
    public CommonResult<List<DeptVO>> getUserDeptList() {
        return success(deptService.getUserDeptList(WebFrameworkUtils.getLoginUserId()));
    }


}
